package com.zyx.flinkdemo.sql.time;

import com.zyx.flinkdemo.pojo.WaterSensor;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

import java.time.Duration;

import static org.apache.flink.table.api.Expressions.$;

/**
 * @author zyx
 * @since 2021/5/29 15:49
 * desc: 流中指定事件时间
 */
public class EventTimeByStream {
    public static void main(String[] args) {
        // 获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);
        // 读取数据源
        SingleOutputStreamOperator<WaterSensor> waterSensorDs = env
                .readTextFile("input/flink/sensor.txt")
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String data) throws Exception {
                        String[] split = data.split(",");
                        return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
                    }
                })
                .assignTimestampsAndWatermarks(WatermarkStrategy
                        .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3L))
                        .withTimestampAssigner((SerializableTimestampAssigner<WaterSensor>) (element, recordTimestamp) -> element.getTs()));
        // 流转表时指定 事件时间
        Table table = tableEnv.fromDataStream(waterSensorDs,
                // 可以直接抽取某个字段作为 事件时间 ==>  $("id"), $("ts").rowtime(), $("vc"))
                $("id"), $("ts"), $("vc"), $("rt").rowtime());
        // 打印表信息
        table.printSchema();
    }
}
